package com.edwardsoft.utils;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerUtil {

    private static EntityManagerFactory entityManagerFactory;

    private static Configuration configuration;
    //创建线程局部变量threadLocal，用来保存Jpa的entityManager
    private static final ThreadLocal<EntityManager> threadLocal = new ThreadLocal<EntityManager>();

    //使用静态代码块初始化EntityManagerFactory
    static {
        try {
            entityManagerFactory = Persistence.createEntityManagerFactory("mysqlJPA");
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    //获得EntityManagerFactory
    public static EntityManagerFactory getSessionFactory() {
        return entityManagerFactory;
    }


    //获得ThreadLocal对象管理的entityManager实例
    public static EntityManager getEntityManager() throws HibernateException {
        EntityManager entityManager = threadLocal.get();
        if (entityManager == null || entityManager.isOpen()) {
            if (entityManagerFactory == null) {
                rebuildSessionFactory();
            }
            //通过SessionFactory对象创建Session对象
            entityManager = (entityManagerFactory != null) ? entityManagerFactory.createEntityManager() : null;
            //将新打开的Session实例保存到线程局部变量threadLocal中
            threadLocal.set(entityManager);
        }

        return entityManager;
    }

    //关闭Session实例
    public static void closeEntityManager() throws HibernateException {
        //从线程局部变量threadLocal中获取之前存入的Session实例
        EntityManager entityManager = threadLocal.get();
        threadLocal.set(null);
        if (entityManager != null) {
            entityManager.close();
        }
    }


    //重建SessionFactory
    public static void rebuildSessionFactory() {
        try {
            entityManagerFactory = Persistence.createEntityManagerFactory("mysqlJPA");
        } catch (Exception e) {
            System.out.println("Error Creating SessionFactory ");
            e.printStackTrace();
        }
    }


    //关闭缓存和连接池
    public static void shutdown() {
        getEntityManager().close();
    }
}